package components.editor
{
	import UIFree.uif_component;
	
	import classes.c_uiEvents;
	import classes.c_util;
	
	import flash.display.DisplayObject;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import org.hamcrest.collection.array;
	
	public class c_bitmapMaskElement extends c_holeyElement {
		private var _params: Object;
		public function c_bitmapMaskElement(parent:uif_component, 
											rect:Rectangle, source:DisplayObject, a_holes: Array, a_params: Object) {
			super(parent, rect, source, a_holes);
			bitmap.alpha = 0.01;
			_params = a_params;
		}
		
		override protected function getActions(): Array {
			return [
				{
					caption	: locale.INSERTPHOTO,
					event	: c_uiEvents.OPENFILE
				}
			];
		}
		
		override protected function createHoles(a_holes:Array):void {
			a_holes.forEach(function(hole: Object, i: int, arr: Array): void {
				a_holes[i].elements = new Object();
			});
			super.createHoles(a_holes);
		}
		
		override protected function nameClass(): String {
			return locale.MASK;
		}
		
		override public function get hitMouse(): Boolean {
			return stage?hitTestPoint(stage.mouseX, stage.mouseY):false;
		}
		
		private function getEars(hole: Object): Array {
			const lrIndent: Number = 0.1;
			const tIndent: Number = 0.42;
			
			var a: Array = new Array();
			
			if (_params && _params.ears)
				return _params.ears;
			else {
				a[0] = hole.spot.rect.x + hole.spot.width * lrIndent;
				a[2] = hole.spot.rect.x + hole.spot.width * (1 - lrIndent);
				a[3] = a[1] = hole.spot.rect.y + hole.spot.height * tIndent;
			}
			return a;
		}
		
		public function assignElement(a_element: c_bitmapElement, params: Object): void {
			
			function matrixFromEars(ears: Array): Matrix {
				var mat		: Matrix 	= new Matrix();
				var ap		: Point		= (new Point(ears[2], ears[3])).subtract((new Point(ears[0], ears[1])));
				var scale	: Number 	= 1/ap.length;
				mat.scale(scale, scale);
				mat.rotate(Math.atan2(ap.x, ap.y));
				return mat;
			}
			
			var hole		: Object = getHole(curHole);
			var holeEars	: Array  = getEars(hole);
			
			var a_matrix	: Matrix = matrixFromEars(params.ears);
			var hmat		: Matrix = matrixFromEars(holeEars);
			hmat.translate(params.ears[0], params.ears[1]);
			hmat.invert();
			hmat.concat(a_matrix);
			hmat.translate(holeEars[0], holeEars[1]);
			
			hmat.concat(matrix);
			a_element.matrix = hmat;
			a_element.owner = This;
			
			hole.elements[params.name] = a_element;
		}
		
		public function getElement(elementName: String, holeIndex: int=-1): c_bitmapElement {
			return getHole((holeIndex > -1)?holeIndex:curHole).elements[elementName];
		}
	}
}